import React from 'react';
import _find from 'lodash/find';
import { connect } from 'umi';
import ChildrenTabs from '@/components/ChildrenTabs';

import pageTabUtil from '@/utils/pageTabUtil';
import { parseLocation } from '@/utils/utils';

// 改变key，但是使用历史location，所以不能用tabRoute
function routeTo(targetTab) {
    const { state, ...route } = targetTab.location; // 切换时不要带上历史state
    pageTabUtil.onTabChange({
        location: route,
        tabKey: targetTab.key
    });
}

// 点击选项卡, 更新路由到目标页面, 并触发对应的change事件
const handleTabChange = (keyToSwitch, activedTabs) => {
    const targetTab = _find(activedTabs, { key: keyToSwitch });
    routeTo(targetTab);
};
// 关闭选项卡, 激活相邻的一个选项卡
const afterRemoveTab = (removeKey, nextTabKey, activedTabs) => {
    const targetTab = _find(activedTabs, { key: nextTabKey });
    routeTo(targetTab);
};

const getMenuName = (action, menuItem) => {
    const nameMap = {
        edit: menuItem.editName,
        detail: menuItem.detailName
    };
    return nameMap[action] || menuItem.name;
};

function PageTabs(props) {
    const { children, location, menu } = props;
    const { breadcrumbNameMap } = menu;

    const [pathname, query] = parseLocation(location);
    const menuItem = breadcrumbNameMap[pathname]; // 获取当前路由对应的配置信息

    if (!menuItem || menuItem?.children?.length) return null;
    return (
        <ChildrenTabs
            activeKey={menuItem.path}
            activeTitle={getMenuName(query?.action, menuItem)}
            extraTabProperties={{
                location
            }}
            handleTabChange={handleTabChange}
            afterRemoveTab={afterRemoveTab}
        >
            {children}
        </ChildrenTabs>
    );
}

export default connect(({ menu }) => ({
    menu
}))(PageTabs);
